package org.arain.baseii.common;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.arain.baseii.mapper.SysAttachmentsMapper;
import org.arain.baseii.pojo.SysAttachments;
import org.arain.baseii.upload.CommonUtil;
import org.arain.baseii.upload.SystemUtil;
import org.arain.baseii.upload.UploadPojo;
import org.arain.baseii.upload.UploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 
* <p>Title:CommonServiceImpl </p>
* @author Arain
* @date2017年8月31日
 */
@Service
public class CommonServiceImpl<T> implements CommonService<T>{
	@Autowired
	private SysAttachmentsMapper sysAttachmentsMapper;
	
	protected Class<T> entityClass;
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public CommonServiceImpl() {
		try {
			this.entityClass = ((Class) ((java.lang.reflect.ParameterizedType) super.getClass().getGenericSuperclass())
					.getActualTypeArguments()[0]);
		} catch (Exception e) {
			this.entityClass = null;
		}
	}

	@Override
	public T jsonToObject(String filterRules, T t) throws Exception {
		JSONArray array = JSONArray.fromObject(filterRules);
		for (Object object : array) {
			JSONObject jsonObject = JSONObject.fromObject(object);
			if (!jsonObject.isNullObject() && jsonObject != null) {
				String field = (String) jsonObject.get("field");
				String value = (String) jsonObject.get("value");
				if(StringUtils.isNotBlank(field)) {
					Field declaredField = t.getClass().getDeclaredField(field);
					declaredField.setAccessible(true);
					declaredField.set(t, value);
				}
			}
			
		}
		return t;
	}

	@Override
	public UploadResult save_01(HttpServletRequest request, UploadPojo pojo) {
		pojo.setAttachmentsType("3");
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		MultipartHttpServletRequest multiRequest = null;
		if (multipartResolver.isMultipart(request)) {// 如果存在文件
			// 转换成多部分request
			multiRequest = (MultipartHttpServletRequest) request;
		}
		if (org.springframework.util.StringUtils.isEmpty(multiRequest)) {
			return new UploadResult();
		}
		List<MultipartFile> files = multiRequest.getFiles("file");
		for (MultipartFile file : files) {
			String fileName = file.getOriginalFilename();
			if (!StringUtils.isEmpty(fileName)) {
				String suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length());
				//获取tomcat服务器文件程序所在地址 
				String tomcatPath = SystemUtil.getTomcatPath();
				//获取附件的相对地址
				String relativePath = SystemUtil.getAttachmentsPath(pojo.getAttachmentsType(), suffix);
				//附件保存的实际地址
				String path = tomcatPath+relativePath;
//				System.out.println(path);
				try {
					CommonUtil.saveFileByInputStream(file.getInputStream(),path, file.getSize());
					//保存附件表
					SysAttachments sysAttachment=new SysAttachments();
					sysAttachment.setAttachmentsType(pojo.getAttachmentsType());
					sysAttachment.setAttachmentSize(String.valueOf(file.getSize()));
					sysAttachment.setServicePath(SystemUtil.UPLOAD_APP_URL);
					sysAttachment.setAppName(SystemUtil.ATTACHMENTS_APP_NAME);
					sysAttachment.setUploadAppName(SystemUtil.UPLOAD_APP_NANME);
					sysAttachment.setAttachmentPath(relativePath);
					sysAttachment.setAttachmentName(fileName);
					sysAttachment.setAttachmentFormat(suffix);
					sysAttachment.setEnabled(0);
					sysAttachment.setOpTime(new Date());
					
					this.sysAttachmentsMapper.insert(sysAttachment);
					
					UploadResult result = new UploadResult();
					result.setId(sysAttachment.getId().toString());
					result.setUrl(sysAttachment.getServicePath()+sysAttachment.getAppName()+sysAttachment.getAttachmentPath());
					result.setState("SUCCESS");
					result.setOriginal(fileName);
					result.setSize(sysAttachment.getAttachmentSize());
					
					return result;
				} catch (IOException e) {
					e.printStackTrace();
					throw new RuntimeException("网络异常");
				}
			}
		}
		return new UploadResult();
	}
}
